﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using IronCow;
using Milkify.Interfaces;
using Milkify.Data;

namespace Milkify.Views
{
    /// <summary>
    /// Interaction logic for TaskNoteEditControl.xaml
    /// </summary>
    public partial class TaskNoteEditControl : PageFunction<TaskNote>, ITaskNoteEditView
    {
        public TaskNoteEditControl()
        {
            InitializeComponent();
        }

        private void ButtonOK_Click(object sender, RoutedEventArgs e)
        {
            CompleteTaskNoteEdit();
        }

        private void ButtonCancel_Click(object sender, RoutedEventArgs e)
        {
            CancelTaskNoteEdit();
        }

        private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            ((TextBox)sender).SelectAll();
        }

        private void CompleteTaskNoteEdit()
        {
            // Let the databinding do his work.
            BindingExpression be;
            be = TextTitle.GetBindingExpression(TextBox.TextProperty); be.UpdateSource();
            be = TextBody.GetBindingExpression(TextBox.TextProperty); be.UpdateSource();

            // Notify that the task edit is complete.
            if (EditComplete != null)
                EditComplete(this, EventArgs.Empty);

            TaskNoteViewData viewData = ViewData as TaskNoteViewData;
            OnReturn(new ReturnEventArgs<TaskNote>(viewData.TaskNote));
        }

        private void CancelTaskNoteEdit()
        {
            // Notify that the task edit has been cancelled.
            if (EditCancelled != null)
                EditCancelled(this, EventArgs.Empty);

            OnReturn(null);
        }

        #region ITaskNoteEditView Members

        public event EventHandler EditComplete;
        public event EventHandler EditCancelled;

        #endregion

        #region IView Members

        public object ViewData
        {
            get { return DataContext; }
            set { DataContext = value; }
        }

        #endregion
    }
}
